using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class square_move : MonoBehaviour
{
    public Vector2 checkCenter;
    public float CheckDistance = 1.5f;
    public LayerMask PlayerLayer;
    public Transform target;
    public float smoothing;

    private Rigidbody2D my_rigid;
    public enum state
    {
        beleftpush,berightpush, bedowntpush, beuppush,idle,
    }

    public state s;

    // Start is called before the first frame update
    void Start()
    {
        s = state.idle;
    }

    // Update is called once per frame
    void Update()
    {
        physics_check();
        push_byplayer();
    }

    void physics_check()
    {
        RaycastHit2D beleftpush = Raycast(checkCenter, Vector2.right , CheckDistance, PlayerLayer);
        RaycastHit2D berightpush = Raycast(checkCenter, Vector2.left  , CheckDistance, PlayerLayer);
       // RaycastHit2D bedowntpush = Raycast(checkCenter, Vector2.up, CheckDistance, PlayerLayer);
       // RaycastHit2D beuppush = Raycast(checkCenter, Vector2.down, CheckDistance, PlayerLayer);

        if (beleftpush)
        {
            s = state.beleftpush;
        }else if(berightpush){
            s = state.berightpush;
        }
        else
        {
            s = state.idle;
        }
    }

    void push_byplayer()
    {
        if (s == state.beleftpush && Input.GetKeyDown(KeyCode.Q))
        {
            Debug.Log("1111");
            if (transform.position != target.position)
            {
                Vector3 targetpos = target.position;
                //Debug.Log("222");

                transform.position = Vector3.Lerp(transform.position, targetpos, smoothing);
            }
            //transform.position = new Vector3(transform.position.x - 1f, transform.position.y, transform.position.z);
        }
        else if (s == state.berightpush && Input.GetKeyDown(KeyCode.Q))
        {
            if (transform.position != target.position)
            {
                Vector3 targetpos = target.position;


                transform.position = Vector3.Lerp(transform.position, targetpos, smoothing);
            }
            //transform.position = new Vector3(transform.position.x + 1f, transform.position.y, transform.position.z);
        }
        
    }


    RaycastHit2D Raycast(Vector2 offset, Vector2 rayDiraction, float length, LayerMask layer)
    {
        Vector2 pos = transform.position;
        RaycastHit2D hit = Physics2D.Raycast(pos + offset, rayDiraction, length, layer);
        Color color = hit ? Color.red : Color.green;
        Debug.DrawRay(pos + offset, rayDiraction * length, color, 0.2f);
        return hit;
    }

   
}
